package com.teamcenter.rac.massupdate.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ObservableListContentProvider;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.views.properties.IPropertySource;
import org.eclipse.wb.swt.SWTResourceManager;

import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.explorer.common.ISearchResultNavigator;
import com.teamcenter.rac.explorer.common.SearchEngine;
import com.teamcenter.rac.explorer.common.SearchServiceManager;
import com.teamcenter.rac.explorer.common.TCComponentSearch;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentQuery;
import com.teamcenter.rac.kernel.TCComponentType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPropertyDescriptor;
import com.teamcenter.rac.kernel.TCQueryClause;
import com.teamcenter.rac.massupdate.model.SearchCriteria;
import com.teamcenter.rac.massupdate.utils.SourceHelper;
import com.teamcenter.rac.providers.PropertiesLoader;
import com.teamcenter.rac.util.AdapterUtil;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.viewer.listener.ColumnListener;
import com.teamcenter.rac.viewer.view.ViewerHelper;
@SuppressWarnings({"rawtypes","unchecked"})
public class ItemRevisionSearchDialog extends AbstractMassUpdateDialog {
	protected static final String[] ITEM_REV_PROPERTY_NAMES = { "object_string", "object_desc", "release_status_list",
			"owning_user", "owning_group" };
	private Text m_itemIdText;
	private Text m_itemNameText;
	private Text m_itemRevisionIdText;
	protected Button m_searchButton;
	private SearchCriteria m_searchCriteria = new SearchCriteria();
	protected Label m_searchMessageLabel;
	protected WritableList m_searchResults = new WritableList(new ArrayList(), IPropertySource.class);
	private Table m_searchResultsTable;
	private TCComponentItemRevision m_selectedItemRevision;
	private TableViewer m_tableViewer;

	public ItemRevisionSearchDialog(Shell paramShell) {
		super(paramShell);
		setShellStyle(36080);
	}

	public TCComponentItemRevision getResult() {
		return this.m_selectedItemRevision;
	}

	public SearchCriteria getSearchCriteria() {
		return this.m_searchCriteria;
	}

	protected void createButtonsForButtonBar(Composite paramComposite) {
		Button localButton1 = createButton(paramComposite, 0, IDialogConstants.OK_LABEL, false);
		localButton1.setEnabled(false);
		Button localButton2 = createButton(paramComposite, 1, IDialogConstants.CANCEL_LABEL, false);
		localButton2.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent paramAnonymousSelectionEvent) {
				ItemRevisionSearchDialog.this.close();
			}
		});
		this.m_bindingContext = initDataBindings();
		setupAggregateValidationStatus();
		initCommonDataBindings(this.m_bindingContext);
	}

	protected Control createContents(Composite paramComposite) {
		Control localControl = super.createContents(paramComposite);
		setTitle(Messages.ItemRevisionSearchDialog_Title_Search);
		getShell().setText(Messages.ItemRevisionSearchDialog_Title_Search);
		setMessage(getMessageText());
		return localControl;
	}

	protected Control createDialogArea(Composite paramComposite) {
		Composite localComposite1 = (Composite) super.createDialogArea(paramComposite);
		GridLayout localGridLayout = new GridLayout(1, false);
		localGridLayout.verticalSpacing = 0;
		localGridLayout.marginWidth = 0;
		localGridLayout.marginHeight = 0;
		localGridLayout.horizontalSpacing = 0;
		Composite localComposite2 = new Composite(localComposite1, 0);
		localComposite2.setLayoutData(new GridData(4, 4, true, true, 1, 1));
		localComposite2.setLayout(localGridLayout);
		contributeChangeInformationGroup(localComposite2);
		contributeChangeTableGroup(localComposite2);
		this.m_tableViewer.setContentProvider(new ObservableListContentProvider());
		this.m_tableViewer.setInput(this.m_searchResults);
		return localComposite1;
	}

	protected Point getInitialSize() {
		if (dialogSettingExists()) {
			return super.getInitialSize();
		}
		return new Point(650, 600);
	}

	protected String getItemIdSearchProperty() {
		return "items_tag.item_id";
	}

	protected String getItemNameSearchProperty() {
		return "object_name";
	}

	protected String getItemRevisionIdSearchProperty() {
		return "item_revision_id";
	}

	protected String getItemRevisionTypeName() {
		return "ItemRevision";
	}

	protected String getMessageText() {
		return Messages.ItemRevisionSearchDialog_Msg_ItemRevSearch;
	}

	protected String getSaveQueryName() {
		return "__Item_Revision_name_ID_and_rev";
	}

	protected void initCommonDataBindings(DataBindingContext paramDataBindingContext) {
	}

	protected DataBindingContext initDataBindings() {
		DataBindingContext localDataBindingContext = new DataBindingContext();
		ISWTObservableValue localISWTObservableValue1 = SWTObservables.observeText(this.m_itemIdText, 24);
		IObservableValue localIObservableValue1 = BeansObservables.observeValue(this.m_searchCriteria, "itemId");
		localDataBindingContext.bindValue(localISWTObservableValue1, localIObservableValue1, null, null);
		ISWTObservableValue localISWTObservableValue2 = SWTObservables.observeText(this.m_itemNameText, 24);
		IObservableValue localIObservableValue2 = BeansObservables.observeValue(this.m_searchCriteria, "itemName");
		localDataBindingContext.bindValue(localISWTObservableValue2, localIObservableValue2, null, null);
		ISWTObservableValue localISWTObservableValue3 = SWTObservables.observeText(this.m_itemRevisionIdText, 24);
		IObservableValue localIObservableValue3 = BeansObservables.observeValue(this.m_searchCriteria,
				"itemRevisionId");
		localDataBindingContext.bindValue(localISWTObservableValue3, localIObservableValue3, null, null);
		return localDataBindingContext;
	}

	protected void okPressed() {
		setResult();
		super.okPressed();
	}

	private void contributeActualTableColumns(TableViewer paramTableViewer) {
		int[] arrayOfInt = { 130, 120, 100, 120, 120 };
		String[] arrayOfString = ViewerHelper.getTextValues(ITEM_REV_PROPERTY_NAMES);
		ViewerHelper.addViewerColumns(paramTableViewer, ITEM_REV_PROPERTY_NAMES, arrayOfString, null, false);
		int i = this.m_searchResultsTable.getColumnCount();
		for (int j = 0; j < i; j++) {
			TableColumn localTableColumn = this.m_searchResultsTable.getColumn(j);
			localTableColumn.setMoveable(true);
			localTableColumn.setResizable(true);
			localTableColumn.setWidth(arrayOfInt[j]);
			ColumnListener localColumnListener = new ColumnListener(paramTableViewer);
			localTableColumn.addSelectionListener(localColumnListener);
			localTableColumn.addControlListener(localColumnListener);
		}
	}

	private void contributeChangeInformationGroup(Composite paramComposite) {
		GridLayout localGridLayout1 = new GridLayout(1, false);
		localGridLayout1.verticalSpacing = 0;
		localGridLayout1.marginWidth = 0;
		localGridLayout1.marginHeight = 0;
		localGridLayout1.horizontalSpacing = 0;
		Group localGroup = new Group(paramComposite, 0);
		localGroup.setLayoutData(new GridData(4, 16777216, true, false, 1, 1));
		localGroup.setLayout(localGridLayout1);
		localGroup.setText(Messages.ItemRevisionSearchDialog_Grp_SearchCriteria);
		GridLayout localGridLayout2 = new GridLayout(2, false);
		localGridLayout2.marginLeft = 10;
		Composite localComposite1 = new Composite(localGroup, 0);
		localComposite1.setLayoutData(new GridData(4, 16777216, true, true, 1, 1));
		localComposite1.setLayout(localGridLayout2);
		Label localLabel1 = new Label(localComposite1, 0);
		FontData localFontData1 = localLabel1.getFont().getFontData()[0];
		localLabel1.setFont(JFaceResources.getFontRegistry().getBold(localFontData1.getName()));
		localLabel1.setLayoutData(new GridData(131072, 16777216, false, false, 1, 1));
		localLabel1.setText(getItemIdLabel());
		this.m_itemIdText = new Text(localComposite1, 2052);
		this.m_itemIdText.setLayoutData(new GridData(4, 16777216, true, false, 1, 1));
		Label localLabel2 = new Label(localComposite1, 0);
		FontData localFontData2 = localLabel2.getFont().getFontData()[0];
		localLabel2.setFont(JFaceResources.getFontRegistry().getBold(localFontData2.getName()));
		localLabel2.setLayoutData(new GridData(131072, 16777216, false, false, 1, 1));
		localLabel2.setText(getItemNameLabel());
		this.m_itemNameText = new Text(localComposite1, 2052);
		this.m_itemNameText.setLayoutData(new GridData(4, 16777216, true, false, 1, 1));
		Label localLabel3 = new Label(localComposite1, 0);
		FontData localFontData3 = localLabel3.getFont().getFontData()[0];
		localLabel3.setFont(JFaceResources.getFontRegistry().getBold(localFontData3.getName()));
		localLabel3.setLayoutData(new GridData(131072, 16777216, false, false, 1, 1));
		localLabel3.setText(getItemRevisionIdLabel());
		this.m_itemRevisionIdText = new Text(localComposite1, 2052);
		this.m_itemRevisionIdText.setLayoutData(new GridData(4, 16777216, true, false, 1, 1));
		Composite localComposite2 = new Composite(localGroup, 0);
		localComposite2.setLayoutData(new GridData(4, 128, true, true, 1, 1));
		localComposite2.setLayout(new GridLayout(2, true));
		this.m_searchMessageLabel = new Label(localComposite2, 0);
		FontData localFontData4 = this.m_searchMessageLabel.getFont().getFontData()[0];
		this.m_searchMessageLabel.setFont(JFaceResources.getFontRegistry().getBold(localFontData4.getName()));
		this.m_searchMessageLabel.setLayoutData(new GridData(131072, 16777216, false, false, 1, 1));
		this.m_searchMessageLabel.setText("");
		this.m_searchButton = new Button(localComposite2, 0);
		this.m_searchButton.setLayoutData(new GridData(131072, 16777216, true, false, 1, 1));
		this.m_searchButton.setText(Messages.ItemRevisionSearchDialog_Title_Search);
		this.m_searchButton.setImage(
				SWTResourceManager.getImage(WizardTargetPage2.class, "/com/teamcenter/rac/aif/images/find_16.png"));
		this.m_searchButton.setEnabled(true);
		this.m_searchButton.setFocus();
		this.m_searchButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent paramAnonymousSelectionEvent) {
				ItemRevisionSearchDialog.this.m_searchButton.setEnabled(false);
				ItemRevisionSearchDialog.this.m_searchMessageLabel
						.setText(Messages.ItemRevisionSearchDialog_Label_SearchMessage);
				ItemRevisionSearchDialog.this.m_searchMessageLabel.pack();
				ItemRevisionSearchDialog.this.performSearch();
			}
		});
		getShell().setDefaultButton(this.m_searchButton);
	}

	private void contributeChangeTableGroup(Composite paramComposite) {
		Group localGroup = new Group(paramComposite, 0);
		localGroup.setLayoutData(new GridData(4, 4, true, true, 1, 1));
		localGroup.setText(Messages.ItemRevisionSearchDialog_Grp_SearchResults);
		GridLayout localGridLayout1 = new GridLayout(2, false);
		localGridLayout1.verticalSpacing = 0;
		localGridLayout1.marginWidth = 0;
		localGridLayout1.marginHeight = 0;
		localGridLayout1.horizontalSpacing = 0;
		localGroup.setLayout(localGridLayout1);
		Composite localComposite = new Composite(localGroup, 0);
		localComposite.setLayoutData(new GridData(4, 4, true, true, 1, 1));
		GridLayout localGridLayout2 = new GridLayout(1, false);
		localGridLayout2.verticalSpacing = 0;
		localGridLayout2.marginWidth = 0;
		localGridLayout2.marginHeight = 0;
		localGridLayout2.horizontalSpacing = 0;
		localComposite.setLayout(localGridLayout2);
		this.m_tableViewer = new TableViewer(localComposite, 68356);
		this.m_tableViewer.setComparator(new AbstractMassUpdateDialog.IC_PropertyColumnViewerSorter());
		this.m_searchResultsTable = this.m_tableViewer.getTable();
		this.m_searchResultsTable.setLinesVisible(true);
		this.m_searchResultsTable.setHeaderVisible(true);
		this.m_searchResultsTable.setLayoutData(new GridData(4, 4, true, true, 1, 1));
		this.m_searchResultsTable.addSelectionListener(new SelectionAdapter() {
			public void widgetDefaultSelected(SelectionEvent paramAnonymousSelectionEvent) {
				ItemRevisionSearchDialog.this.setResult();
				ItemRevisionSearchDialog.this.close();
			}

			public void widgetSelected(SelectionEvent paramAnonymousSelectionEvent) {
				ISelection localISelection = ItemRevisionSearchDialog.this.m_tableViewer.getSelection();
				if (localISelection.isEmpty()) {
					ItemRevisionSearchDialog.this.getButton(0).setEnabled(false);
				} else {
					ItemRevisionSearchDialog.this.getButton(0).setEnabled(true);
				}
			}
		});
		contributeActualTableColumns(this.m_tableViewer);
		new Label(localGroup, 0);
	}

	private String getItemIdLabel() {
		String str = getLabel("item_id");
		if (str == null) {
			return Messages.ItemRevisionSearchDialog_Label_ItemId;
		}
		return str;
	}

	private String getItemNameLabel() {
		String str = getLabel("object_name");
		if (str == null) {
			return Messages.ItemRevisionSearchDialog_Label_ItemName;
		}
		return str;
	}

	private TCComponentType getItemRevisionComponentType() {
		try {
			return getTCSession().getTypeComponent(getItemRevisionTypeName());
		} catch (TCException localTCException) {
			Logger.getLogger(ItemRevisionSearchDialog.class).error(localTCException.getLocalizedMessage(),
					localTCException);
		}
		return null;
	}

	private String getItemRevisionIdLabel() {
		String str = getLabel("item_revision_id");
		if (str == null) {
			return Messages.ItemRevisionSearchDialog_Label_ItemRevisionId;
		}
		return str;
	}

	private String getLabel(String paramString) {
		try {
			TCComponentType localTCComponentType = getItemRevisionComponentType();
			TCPropertyDescriptor localTCPropertyDescriptor = localTCComponentType.getPropertyDescriptor(paramString);
			if (localTCPropertyDescriptor != null) {
				return localTCPropertyDescriptor.getDisplayName();
			}
		} catch (TCException localTCException) {
			Logger.getLogger(ItemRevisionSearchDialog.class).error(localTCException.getLocalizedMessage(),
					localTCException);
		}
		return null;
	}

	public void performSearch() {
		AbstractAIFOperation local4 = new AbstractAIFOperation() {
			@SuppressWarnings("deprecation")
			public void executeOperation() throws Exception {
				try {
					ArrayList localArrayList1 = new ArrayList(3);
					ArrayList localArrayList2 = new ArrayList(3);
					if ((ItemRevisionSearchDialog.this.m_searchCriteria.getItemId() != null)
							&& (!ItemRevisionSearchDialog.this.m_searchCriteria.getItemId().isEmpty())) {
						localArrayList1.add(ItemRevisionSearchDialog.this.getItemIdSearchProperty());
						localArrayList2.add(ItemRevisionSearchDialog.this.m_searchCriteria.getItemId());
					}
					if ((ItemRevisionSearchDialog.this.m_searchCriteria.getItemName() != null)
							&& (!ItemRevisionSearchDialog.this.m_searchCriteria.getItemName().isEmpty())) {
						localArrayList1.add(ItemRevisionSearchDialog.this.getItemNameSearchProperty());
						localArrayList2.add(ItemRevisionSearchDialog.this.m_searchCriteria.getItemName());
					}
					if ((ItemRevisionSearchDialog.this.m_searchCriteria.getItemRevisionId() != null)
							&& (!ItemRevisionSearchDialog.this.m_searchCriteria.getItemRevisionId().isEmpty())) {
						localArrayList1.add(ItemRevisionSearchDialog.this.getItemRevisionIdSearchProperty());
						localArrayList2.add(ItemRevisionSearchDialog.this.m_searchCriteria.getItemRevisionId());
					}
					int i = 0;
					ISearchResultNavigator localISearchResultNavigator = null;
					if (!localArrayList1.isEmpty()) {
						TCComponentQuery localTCComponentQuery = SearchServiceManager
								.getInstance(ItemRevisionSearchDialog.this.getTCSession())
								.getSystemDefinedQuery(ItemRevisionSearchDialog.this.getSaveQueryName());
						if (localTCComponentQuery != null) {
							ArrayList localArrayList3 = new ArrayList();
							TCQueryClause[] arrayOfTCQueryClause1 = localTCComponentQuery.describe();
							Iterator localIterator = localArrayList1.iterator();
							Object localObject;
							while (localIterator.hasNext()) {
								localObject = (String) localIterator.next();
								TCQueryClause[] arrayOfTCQueryClause2;
								int k = (arrayOfTCQueryClause2 = arrayOfTCQueryClause1).length;
								for (int j = 0; j < k; j++) {
									TCQueryClause localTCQueryClause = arrayOfTCQueryClause2[j];
									if (localTCQueryClause.getAttributeName().equals(localObject)) {
										localArrayList3.add(localTCQueryClause.getUserEntryNameDisplay());
										break;
									}
								}
							}
							if (localArrayList1.size() == localArrayList3.size()) {
								i = 1;
								localObject = new TCComponentSearch(localTCComponentQuery);
								((TCComponentSearch) localObject).setCrieria(
										(String[]) localArrayList3.toArray(new String[localArrayList3.size()]),
										(String[]) localArrayList2.toArray(new String[localArrayList2.size()]));
								((TCComponentSearch) localObject).setCriteriaInternalValues(
										(String[]) localArrayList2.toArray(new String[localArrayList2.size()]));
								localISearchResultNavigator = SearchEngine
										.getInstance(ItemRevisionSearchDialog.this.getTCSession())
										.performSearch((TCComponentSearch) localObject, null);
							} else {
								throw new TCException(Messages.ItemRevisionSearchDialog_Msg_InvalidPropertyToSearch);
							}
						}
					}
					final boolean bool = (localArrayList1.isEmpty()) || (i != 0);
					ItemRevisionSearchDialog.this.m_searchResults.getRealm().asyncExec(new Runnable() {
						public void run() {
							ItemRevisionSearchDialog.this.m_searchResults.clear();
							if (!bool) {
								MessageBox.post(ItemRevisionSearchDialog.this.getShell(),
										Messages.ItemRevisionSearchDialog_Msg_TargetSearchComponentNotAvailable,
										Messages.ItemRevisionSearchDialog_Title_Search, 1);
							}
						}
					});
					ItemRevisionSearchDialog.this.processSearchResults(localISearchResultNavigator);
				} catch (TCException localTCException) {
					Logger.getLogger(ItemRevisionSearchDialog.class).error(localTCException.getLocalizedMessage(),
							localTCException);
					// ItemRevisionSearchDialog.this.m_searchResults.getRealm().asyncExec(new
					// Runnable() {
					// public void run() {
					MessageBox.post(ItemRevisionSearchDialog.this.getShell(), localTCException.getLocalizedMessage(),
							Messages.ItemRevisionSearchDialog_Title_Search, 1);
					// }
					// });
				}
			}
		};
		getTCSession().queueOperation(local4);
	}

	protected void processSearchResults(ISearchResultNavigator paramISearchResultNavigator) {
		final ISearchResultNavigator localISearchResultNavigator = paramISearchResultNavigator;
		this.m_searchResults.getRealm().asyncExec(new Runnable() {
			public void run() {
				ItemRevisionSearchDialog.this.m_searchResults.clear();
				int i = 0;
				if (localISearchResultNavigator != null) {
					List localObject1 = localISearchResultNavigator.getAllFoundObjects();
					i = localISearchResultNavigator.getTotalObjectCount();
					if (localObject1 != null) {
						PropertiesLoader.getInstance().loadProperties(((List) localObject1).toArray(),
								ItemRevisionSearchDialog.ITEM_REV_PROPERTY_NAMES, true);
						Iterator localIterator = ((List) localObject1).iterator();
						while (localIterator.hasNext()) {
							Object localObject2 = localIterator.next();
							TCComponentItemRevision localTCComponentItemRevision = (TCComponentItemRevision) localObject2;
							IPropertySource localIPropertySource = (IPropertySource) AdapterUtil
									.getAdapter(localTCComponentItemRevision, IPropertySource.class);
							ItemRevisionSearchDialog.this.m_searchResults.add(localIPropertySource);
						}
					}
				}
				Object localObject1 = new StringBuffer(String.valueOf(i));
				((StringBuffer) localObject1).append(" ");
				((StringBuffer) localObject1).append(Messages.ItemRevisionSearchDialog_Label_SearchResultCount);
				ItemRevisionSearchDialog.this.m_searchMessageLabel.setText(((StringBuffer) localObject1).toString());
				ItemRevisionSearchDialog.this.m_searchMessageLabel.pack();
				ItemRevisionSearchDialog.this.m_searchButton.setEnabled(true);
			}
		});
	}

	private void setResult() {
		if (this.m_tableViewer == null) {
			return;
		}
		ISelection localISelection = this.m_tableViewer.getSelection();
		if ((localISelection != null) && (!localISelection.isEmpty())
				&& ((localISelection instanceof IStructuredSelection))) {
			StructuredSelection localStructuredSelection = (StructuredSelection) localISelection;
			if (localStructuredSelection.getFirstElement() != null) {
				IPropertySource localIPropertySource = (IPropertySource) AdapterUtil
						.getAdapter(localStructuredSelection.getFirstElement(), IPropertySource.class);
				if (localIPropertySource != null) {
					TCComponent localTCComponent = SourceHelper.getAssociatedComponent(localIPropertySource,
							getTCSession());
					if (localTCComponent != null) {
						this.m_selectedItemRevision = ((TCComponentItemRevision) localTCComponent);
					}
				}
			}
		}
	}
}
